import { login } from '@/services/user';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { message } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less';

export default () => {
  // const [captcha, setCaptcha] = useState('');
  const [captchaUrl, setCaptchaUrl] = useState(
    'http://localhost:7001/api/captcha?' + Date.now(),
  );
  const initCaptcha = () => {
    const baseUrl = 'http://localhost:7001';
    setCaptchaUrl(`${baseUrl}/api/captcha?${Date.now()}`);
  };
  const handleSubmit = async (values: any) => {
    try {
      const res = await login({ ...values });
      localStorage.setItem('token', res.token);
      localStorage.setItem('refreshToken', res.refreshToken);
      message.success('登录成功');
      history.push('/');
    } catch (e) {
      message.error(e.message || '登录失败');
    }
  };
  useEffect(() => {
    initCaptcha();
  }, []);
  return (
    <div
      className={styles.container}
      style={{
        background: 'url(/images/login-bg.jpg) center/cover',
        position: 'relative',
      }}
    >
      <div
        style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%,-50%)',
        }}
      >
        <LoginForm
          style={{ margin: 20 }}
          title="企业级权限管理后台"
          onFinish={handleSubmit}
        >
          <ProFormText
            name="username"
            placeholder="用户名"
            initialValue="admin"
            rules={[{ required: true }]}
          />
          <ProFormText.Password
            name="password"
            placeholder="密码"
            initialValue="123456"
            rules={[{ required: true }]}
          />
          <ProFormText
            name="captcha"
            placeholder="图形验证码"
            rules={[{ required: true, message: '请输入图形验证码' }]}
            fieldProps={{
              suffix: (
                <img
                  src={captchaUrl}
                  onClick={initCaptcha}
                  alt="captcha"
                  style={{ height: 28, cursor: 'pointer' }}
                />
              ),
            }}
          />
        </LoginForm>
      </div>
    </div>
  );
};
